import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:oramemo/common/langs/text_key.dart';
import 'package:oramemo/common/styles/colors.dart';
import 'package:oramemo/core/controllers/device_controller.dart';
import 'package:oramemo/pages/device/relation_select_page.dart';
import 'package:oramemo/pages/device/device_name_edit_page.dart';
import 'package:oramemo/pages/transcription/ai_transcription/ai_transcription_logic.dart';
import 'package:oramemo/widget/my_button.dart';

import 'device_detail_logic.dart';
import 'ercode_view.dart';

class DeviceDetailPage extends StatefulWidget {
  const DeviceDetailPage({Key? key}) : super(key: key);

  @override
  State<DeviceDetailPage> createState() => _DeviceDetailPageState();
}

class _DeviceDetailPageState extends State<DeviceDetailPage> {
  @override
  Widget build(BuildContext context) {
    Get.put(DeviceDetailLogic());
    RelationSelectController relationController =
        Get.put(RelationSelectController());
    return Scaffold(
      appBar: AppBar(
        title: const Text(''),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () => Get.back(),
        ),
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(height: 20.h),

              // 头像部分
              _buildHeaderSection(),

              SizedBox(height: 20.h),

              // 设备信息卡片
              Container(
                margin: EdgeInsets.symmetric(horizontal: 16.w),
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                decoration: ShapeDecoration(
                  color: Color(0xFFF3F5F9),
                  shape: RoundedRectangleBorder(
                    side: BorderSide(width: 1, color: Color(0x1992B9FF)),
                    borderRadius: BorderRadius.circular(36.r),
                  ),
                ),
                child: GetBuilder<DeviceDetailLogic>(builder: (logic) {
                  return Column(
                    children: [
                      SizedBox(height: 20.h),
                      // 设备名称
                      _buildInfoItem(
                        title: '设备名',
                        value: logic.deviceName.value ?? '--',
                        showArrow: true,
                        onTap: () async {
                          // 修改设备名称
                          // 打开设备名称编辑页面
                          final result = await Get.to(
                              () => const DeviceNameEditPage(initialName: ''));

// 如果用户点击保存，result 将包含新的设备名称
                          if (result != null) {
                            // 处理新的设备名称
                            logic.updateDevice(name: result);
                          }
                        },
                      ),

                      const Divider(
                          height: 1, thickness: 1, color: Color(0xFFEEEEEF)),

                      // 绑定账号
                      _buildInfoItem(
                        title: '该时光机绑定账号',
                        value: '',
                        showArrow: false,
                      ),

                      const Divider(
                          height: 1, thickness: 1, color: Color(0xFFEEEEEF)),

                      // 与该时光机的关系
                      _buildInfoItem(
                        title: '与该时光机的关系',
                        value:
                            relationController.selectedRelation?.relationName ??
                                '',
                        showArrow: true,
                        onTap: () async {
                          // _showRelationPicker();
                          // 打开关系选择页面
                          final result = await Get.to(
                              () => RelationSelectPage(initialRelation: ''));

// 如果用户点击保存，result 将包含选择的关系
                          if (result != null) {
                            // logic.updateDevice(entity)
                            logic.update();
                          }
                        },
                      ),
                      const Divider(
                          height: 1, thickness: 1, color: Color(0xFFEEEEEF)),

                      const SizedBox(height: 20),
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: 16.w),
                          child: const Text(
                            '设备圈子二维码',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w500,
                              color: Colors.black87,
                            ),
                          ),
                        ),
                      ),

                      ErcodeView(),
                    ],
                  );
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInfoItem({
    required String title,
    required String value,
    bool showArrow = false,
    VoidCallback? onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Colors.black87,
              ),
            ),
            Row(
              children: [
                Text(
                  value,
                  style: const TextStyle(
                    fontSize: 16,
                    color: Color(0xFF888992),
                  ),
                ),
                if (showArrow) ...[
                  const SizedBox(width: 8),
                  const Icon(
                    Icons.arrow_forward_ios,
                    size: 16,
                    color: Color(0xFF888992),
                  ),
                ],
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeaderSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 28.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 头像
          // Container(
          //   width: 80.w,
          //   height: 80.w,
          //   decoration: const BoxDecoration(
          //     shape: BoxShape.circle,
          //     color: Color(0xFFEEEEEF),
          //   ),
          //   child: const Center(
          //     child: Icon(
          //       Icons.person_outline,
          //       size: 40,
          //       color: Color(0xFF888992),
          //     ),
          //   ),
          // ),
          SizedBox(width: 30.w),

          // 名称和编辑按钮
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                GetBuilder<DeviceDetailLogic>(builder: (logic) {
                  return Text(
                    logic.device?.device?.deviceName ?? '--',
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  );
                }),
                // SizedBox(height: 8.h),
                // Row(
                //   children: [
                //     Text(
                //       '点击完善信息',
                //       style: TextStyle(
                //         fontSize: 14.sp,
                //         color: Colors.grey,
                //       ),
                //     ),
                //     SizedBox(width: 4.w),
                //     Icon(
                //       Icons.edit,
                //       size: 16.sp,
                //       color: Colours.app_main,
                //     ),
                //   ],
                // ),
              ],
            ),
          ),
          MyButton(
            minWidth: 79.w,
            minHeight: 32.h,
            backgroundColor: const Color(0xFFCCCCD0),
            fontSize: 14.sp,
            radius: 12.r,
            onPressed: () {
              _showUnbindConfirmation();
            },
            text: '解绑',
          )
        ],
      ),
    );
  }

  // 显示解绑确认弹窗
  void _showUnbindConfirmation() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.r),
              topRight: Radius.circular(20.r),
            ),
          ),
          padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 20.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // 标题
              Text(
                '温馨提示',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
              SizedBox(height: 24.h),

              // 提示文本
              Text(
                '解绑后你将不可查看设备。',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.black87,
                ),
              ),
              SizedBox(height: 32.h),

              // 管理员权限转移
              // Text(
              //   '管理员权限转移至',
              //   style: TextStyle(
              //     fontSize: 16.sp,
              //     color: Colors.black87,
              //   ),
              // ),
              // SizedBox(height: 16.h),
              //
              // // 用户选择区域
              // Row(
              //   mainAxisAlignment: MainAxisAlignment.center,
              //   children: [
              //     // 用户1
              //     _buildUserOption('用户名'),
              //     SizedBox(width: 40.w),
              //     // 用户2
              //     _buildUserOption('用户名'),
              //   ],
              // ),
              // SizedBox(height: 40.h),

              // 确认解绑按钮
              Container(
                width: double.infinity,
                height: 50.h,
                child: ElevatedButton(
                  onPressed: () {
                    // 执行解绑操作

                    DeviceDetailLogic logic = Get.find();
                    if (logic.device?.device?.id?.isNotEmpty == true) {
                      _unbindDevice(logic.device!.device!.id!);
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFF3A3A47),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25.r),
                    ),
                  ),
                  child: Text(
                    '确认解绑',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
              SizedBox(height: MediaQuery.of(context).padding.bottom + 16.h),
            ],
          ),
        );
      },
    );
  }

  Future<void> _unbindDevice(String id) async {
    final DeviceController controller = Get.find();
    try {
      await controller.unbindDevice(id);
      final AiTranscriptionLogic aiTranscriptionLogic = Get.find();
      aiTranscriptionLogic.requestDevices();
      Toast.show(TextKey.deviceUnbindSuccess.tr);
      Get.back();
      Get.back();
      Get.back();
    } catch (e) {
      Toast.show('${TextKey.deviceUnbindFailed.tr}$e');
    }
  }

  // 构建用户选项
  Widget _buildUserOption(String userName) {
    return Column(
      children: [
        Container(
          width: 80.w,
          height: 80.w,
          decoration: BoxDecoration(
            color: Color(0xFFF5F5F5),
            borderRadius: BorderRadius.circular(10.r),
          ),
          child: Center(
            child: Icon(
              Icons.person,
              size: 40.sp,
              color: Colors.grey,
            ),
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          userName,
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.black87,
          ),
        ),
      ],
    );
  }
}
